from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from goods.models import Kinds, Merchant, Category, Goods


# Create your views here.
from utils.QiNiuTools import QiniuTool


class FindMerchant(APIView):

    def get(self,request):
        """
        模糊查询获取商家
        """
        name=request.query_params.get('name')
        print(name)
        mers=Merchant.objects.filter(name__contains=name)
        _list=[]
        for i in mers:
            _goods = []
            for j in i.goods_set.all()[:3]:
                _goods.append({
                    'id':j.id,
                    'sku_name': j.sku_name,
                    'price': j.price,
                    'img': j.img,
                })
            _list.append({
                'id':i.id,
                'name':i.name,
                'user': i.avatar,
                'start_send': i.start_send,
                'sending': i.sending,
                'average': i.average,
                'business_time': i.business_time,
                'goods': _goods,
            })
        return Response({
            'code':200,
            'msg': '搜索商家成功',
            'data': _list,
        })


class KindsView(APIView):
    # 获取所有商家分类
    def get(self,request):
        data=Kinds.objects.all()
        _list=[]
        for i in data:
            _list.append({
                'id':i.id,
                'name': i.cate_name,
                'img': i.img,
            })
        return Response({
            'code':200,
            'msg':'获取分类成功',
            'data':_list
        })

    def post(self,request):
        # 添加商家分类
        name=request.data.get('name')
        img=request.data.get('img')

        if not all([name,img]):
            return Response({'code':400,'msg':'参数错误'})
        try:
            Kinds.objects.get(cate_name=name)
            return Response({'code': 400, 'msg': '分类已存在'})
        except Exception as e:
            try:
                Kinds.objects.create(cate_name=name,img=img)
            except Exception as e:
                print(e)
                return Response({'code':400,'msg':'添加分类失败'})
            return Response({'code': 200, 'msg': '添加分类成功'})

    # def

class MerchantView(APIView):

    def get(self,request):
        # 获取所有商家
        merchants=Merchant.objects.all()
        _list=[]
        for i in merchants:
            _goods = []
            for j in i.goods_set.all()[:3]:
                _goods.append({
                    'id': j.id,
                    'sku_name': j.sku_name,
                    'price': j.price,
                    'img': j.img,
                })
            _list.append({
                'id': i.id,
                'name': i.name,
                'avatar': i.avatar,
                'start_send': i.start_send,
                'sending': i.sending,
                'average': i.average,
                'business_time': i.business_time,
                'business_status': '营业中' if i.business_status else '休息中',
                'goods': _goods,
            })
        return Response({
            'code': 200,
            'msg': '获取所有商家成功',
            'data': _list,
        })




class Merchant_one(APIView):
    def get(self,request,id):
        # 获取单个商家
        try:
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'商家不存在'})
        cates = []
        for i in mer.category_set.all():
            _goods = []
            for j in i.goods_set.all():
                _goods.append({
                    'id': j.id,
                    'name': j.sku_name,
                    'price': j.price,
                    'img': j.img,
                    'instruction': j.instruction,
                    'sell_price': j.selling_price,
                    'count': j.count,
                    'stock': j.stock,
                })
            cates.append({
                'id': i.id,
                'cate_name': i.cate_name,
                'goods': _goods,
            })
            print(mer.goods_set.values_list('count'))
        return Response({
            'code': 200,
            'msg': '获取商家详情成功',
            'data': {
                'id': mer.id,
                'name': mer.name,
                'avatar': mer.avatar,
                'start_send': mer.start_send,
                'sending': mer.sending,
                'average': mer.average,
                'kind_name': mer.kind.cate_name,
                'sum_num': 1,
                'cate': cates
            },
        })

class KindMerchant(APIView):
    # 获取分类下的商家
    def get(self,request,id):
        try:
            kind=Kinds.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'分类不存在'})
        _list=[]
        # _list.append(kind.merchant_set.all())
        for i in kind.merchant_set.all():
            _goods = []
            for j in i.goods_set.all()[:3]:
                _goods.append({
                    'id': j.id,
                    'sku_name': j.sku_name,
                    'price': j.price,
                    'img': j.img,
                })
            _list.append({
                'id': i.id,
                'name': i.name,
                'user': i.avatar,
                'start_send': i.start_send,
                'sending': i.sending,
                'average': i.average,
                'business_time': i.business_time,
                'goods': _goods,
            })
        return Response({
            'code': 200,
            'msg': '获取分类商家成功',
            'kind':kind.cate_name,
            'data': _list,
        })

class Upload(APIView):
    def post(self,request):
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        #  FILES;获取前端图片
        files=request.FILES.get('file')
        print('>>>>>>>>>>>>',files)
        print('>>>>>>>>>>>>',files.name,files.file)
        # 图片写入位置
        file_dir=settings.STATICFILES_DIRS[2]
        # file_dir='http://127.0.0.1:8000/static/merchant'
        print("图片路径前缀》》》",file_dir)
        # 拼接图片路径
        file_name=file_dir+'/'+files.name
        print('完整图片路径》》》',file_name)
        # 写入指定文件
        with open(file_name,'wb') as f:
            # 读取图片字节流写入文件
            f.write(files.file.read())
        rsp = QiniuTool().upload('goods/' + files.name)
        if rsp:
            return Response({
                'code': 200,
                'msg': '上传成功',
                'url': 'http://rmd3r0mox.hn-bkt.clouddn.com/'+rsp,
                'files_name': files.name
            })
class CateGoods(APIView):

    def get(self, request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        cate = Category.objects.filter(id=id)
        if not cate:
            return Response({'code':400,'msg':'商品分类不存在'})
        try:
            data=Goods.objects.filter(cate_id=id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'获取分类下的商品失败'})
        _list = []
        for i in data:
            _list.append({
                'name': i.sku_name,
                'price': i.price,
                'sell_price': i.selling_price,
                'img': i.img,
                'instruction': i.instruction,
                'count': i.count,
                'stock': i.stock,
                'cate_id': i.cate_id,
                'merchant_id': i.merchant_id,
                'online': i.online,
            })
        return Response({
            'code':200,
            'msg':'获取分类下的商品成功',
            'data':_list
        })
class GoodsView(APIView):
    def get(self,request,id):
        try:
            good=Goods.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'获取单个商品失败'})

        return Response({
            'code':200,
            'msg':'获取单个商品成功',
            'data':{
                'name':good.sku_name,
                'id':good.id,
                'price': good.price,
                'sell_price': good.selling_price,
                'img': good.img,
                'instruction': good.instruction,
                'count': good.count,
                'stock': good.stock,
                'cate_id': good.cate_id,
                'merchant_id': good.merchant_id,
                'online': good.online,
            }
        })